
<#include "/head.ftl" />
<div id="pg_margins">
<div id="col1"><#include "/sidebar.ftl" /></div>
<div id="col2">

<div class="location">角色管理</div>

<div class="massaction"><a href="javascript:addRole();">添加</a></div>

<div style="float:left;width:100%;">
	<table id="listTable" class="table table-striped table-bordered table-hover bd_c_1" cellpadding="0" cellspacing="0"></table>
</div>

</div>			
</div>
<#include "modal.ftl" />
<script>
    var $table = $('#listTable');
    var $param = {};

    $(function () {
        // bootstrap table初始化
        $param = {
            url: '/role/list',
            striped: false,
            pagination: true,
            paginationLoop: false,
            sidePagination: 'server',
            smartDisplay: false,
            striped: true,
            idField: 'id',
            sortName: 'id',
            sortOrder: 'desc',
            onLoadSuccess: function() {
            	$('#listTable thead tr').attr("class", "headings");
            },
            columns: [
                {field: 'id', title: '编号', align: 'center', valign: 'middle'},
                {field: 'name', title: '名称', align: 'center', valign: 'middle'},
                {
                    field: 'id',
                    title: '操作',
                    align: 'center',
                    valign: 'middle',
                    formatter: 'operateFormatter',
                    clickToSelect: false
                }
            ]
        };
        $table.bootstrapTable($param);
    });

    function operateFormatter(value, row, index) {
        var action = [];
        action.push('<a href="javascript:;" onclick="updateRole(' + row.id + ')">修改</a>');
        action.push('<a href="javascript:;" onclick="deleteRole(' + row.id + ')">删除</a>');
        return action.join('&nbsp;&nbsp;|&nbsp;&nbsp;');
    }

    function searchRole() {
        $table.bootstrapTable('destroy').bootstrapTable($param);
    }
    
    function getFunctions() {
    	var perm = $('#perm').val();
    	if ($("#saveRole #functions").html()) {
		 	$('#saveForm input[name="function"]').each(function(){
            	var checked = perm.includes($(this).val()) || perm == "all" ? true : false;
		     	$(this).prop("checked", checked);
		 	});
		 	var allchecked = $('#saveForm input[name="function"]').length == $('#saveForm input[name="function"]:checked').length;
		 	$("#saveForm #allfunc").prop("checked", allchecked);
    		return;
    	}
        $.get("/function/list?limit=100", function(res) {
            if (!res.rows) {
                return false;
            }
            var options = '<label class="checkbox-inline"><input id="allfunc" type="checkbox" value="">全选</label>';
            res.rows.forEach((row) => {
            	var checked = perm.includes(row.controller) || perm == "all" ? ' checked' : '';
            	options += '<label class="checkbox-inline"><input name="function" type="checkbox" value="' + row.controller + '"' + checked + '>' + row.name + '</label>';
            });
            $("#saveRole #functions").html(options);
		 	var allchecked = $('#saveForm input[name="function"]').length == $('#saveForm input[name="function"]:checked').length;
		 	$("#saveForm #allfunc").prop("checked", allchecked);
            $("#saveForm #allfunc").change(function() {
            	var that = this;
			 	$('#saveForm input[name="function"]').each(function(){  
			     	$(this).prop("checked", $(that).is(":checked"));
			 	});
            });
            $('#saveForm input[name="function"]').change(function() {
            	if ($(this).is(":checked")) {
				 	var allchecked = $('#saveForm input[name="function"]').length == $('#saveForm input[name="function"]:checked').length;
				 	$("#saveForm #allfunc").prop("checked", allchecked);
            	} else {
				 	$("#saveForm #allfunc").prop("checked", false);
            	}
            });
        });
    }

    function addRole() {
        $("#saveRole #saveForm")[0].reset();
        $("#saveRole #saveForm #id").val("");
        $("#saveRole #saveForm #perm").val("");
        $("#saveRole .modal-title").html("角色添加");
        $("#saveRole").modal("show");
        $(".modal").css("z-index", 998);
        $(".modal-backdrop").css("z-index", 997);
        getFunctions();
    }

    function updateRole(id) {
        $("#saveRole #saveForm")[0].reset();
        $("#saveRole .modal-title").html("角色修改");
        $.get("/role/info?id=" + id, function(res) {
            if (!res.data) {
                showMsgFail(res.message ? res.message : "请求失败");
                return false;
            }
            $("#saveRole #id").val(res.data.id);
            $("#saveRole #rid").val(res.data.rid);
            $("#saveRole #name").val(res.data.name);
            $("#saveRole #perm").val(res.data.perm);
            $("#saveRole").modal("show");
            $(".modal").css("z-index", 998);
            $(".modal-backdrop").css("z-index", 997);
            getFunctions();
        });
    }
    
    function saveRole() {
	    var perms = new Array();  
	 	$('#saveForm input[name="function"]:checked').each(function(){  
	     	perms.push($(this).val());
	 	});
    	$('#saveForm #perm').val(perms.join(','));
        var fields = $('#saveForm').serializeArray();
        var data = {};
        $.each(fields, function(index, field) {
            if (field.value) data[field.name] = field.value;
        })
        if (!data["name"]) {
            showMsgFail("名称必填");
            return false;
        }
        $.ajax({
            url: "/role/save",
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(res) {
                if (res.code != "0200") {
                    showMsgFail(res.message ? res.message : "请求失败");
                    return false;
                }
                $("#saveRole").modal("hide");
                searchRole();
            },
            error: function(e) {
                showMsgFail("请求失败");
            }
        });
    }
    
    function deleteRole(id) {
        confirm("确认删除该角色？", function() {
            $.ajax({
                url: "/role/delete?id=" + id,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(res) {
                    if (res.code != "0200") {
                        showMsgFail(res.message ? res.message : "请求失败");
                        return false;
                    }
                    searchRole();
                },
                error: function(e) {
                    showMsgFail("请求失败");
                }
            });
        });
    }
</script>
<#include "/foot.ftl" />
